import { AppState } from '@app/providers/store/store'
import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import { setTokens } from '@shared/lib/store/tokenSlice'
import type { BaseQueryFn, FetchArgs, FetchBaseQueryError } from '@reduxjs/toolkit/query'

interface ExtraOptionsWithDelay {
  delay?: number
}

const url = process.env.BASE_URL_API
const baseQuery = fetchBaseQuery({
  baseUrl: `${url}`,
  prepareHeaders: (headers, { getState }) => {
    const accessToken = (getState() as AppState).token.accessToken
    headers.set('authorization', `Bearer ${accessToken ?? ''}`)
    return headers
  },
})

export const baseQueryWithDelay: BaseQueryFn<
  FetchArgs | string,
  unknown,
  FetchBaseQueryError,
  ExtraOptionsWithDelay
> = async (args, api, extraOptions) => {
  const { dispatch, getState } = api
  const expireToken = (getState() as AppState).token.expireToken

  if (expireToken && expireToken < Date.now()) {
    const refreshToken = (getState() as AppState).token.refreshToken
    const response = await fetch(`${url}users/refresh`, {
      // body: JSON.stringify({ refreshToken }),
      headers: {
        'Content-Type': 'application/json',
        authorization: `Bearer ${refreshToken}`,
      },
      method: 'POST',
    })

    if (response.ok) {
      const data = await response.json()
      dispatch(setTokens(data))
    }
  }
  return new Promise((resolve) => {
    setTimeout(async () => resolve(await baseQuery(args, api, extraOptions)), 0)
  })
}
